import json,os
import pandas as pd
import requests
def getData(url):
    """发起请求，返回想要提取的数据"""
    response = requests.get(url)       # 发起get请求
    res_data = []                      #   需要提取的数据
    try:
        if response.status_code == 200:       # 状态码是否为200，200为正常
            json_data = json.loads(response.text)        # 将json字符串转换为python对象
            for i in json_data['more_city']:
                for data in i['city']:
                    res_data.append(data)                 # 将想要的数据追加到res_data中
            saveData(res_data)               # 调用saveData()函数
        else:
            print('状态码错误')
    except:
        exit()
def saveData(data):
    """保存返回提取的数据"""
    code = []
    geo = []
    name = []
    num = []
    # 提取想要的数据
    for i in data:
        code.append(i['codeCity'])
        geo.append(i['geo'])
        name.append(i['name'])
        num.append(i['num'])
    #  创建一个DataFrame对象
    DataFrame = pd.DataFrame({
        'codeCity': code,
        'name': name,
        'num': num,
        'geo': geo
    })
    # 判断文件是否存在，存在则删除再创建，不存在则直接创建
    path = '../data/data.xlsx'
    if not os.path.exists(path):
        DataFrame.to_excel(path, index=False)
    else:
        os.remove(path)
        DataFrame.to_excel(path, index=False)

if __name__ == '__main__':
    url = 'https://map.baidu.com/?newmap=1&reqflag=pcmap&biz=1&from=webmap&da_par=baidu&pcevaname=pc4.1&' \
          'qt=s&c=1&wd=%E7%91%9E%E5%B9%B8&da_src=shareurl&on_gel=1&l=5&gr=1&b=(3742035.22001075,2133851.8799791466;' \
          '19470675.22001075,7204699.879979147)&pn=0&device_ratio=1&auth=SExNR%400AfV99L9fwC00I0WMe0f7EMwUvuxLLLBzzTzR' \
          'tUCCUA7AOOvyuwyS8v7uvkGcuVtvvhguVtvyheuVtvCMGuVtvCQMuVtvIPcuVtvYvjuVtvZgMuVtv%40vcuVtvc3CuVtvcPPuVtcvY1SGpuxEt' \
          'HrQH2eGveh3uVtvh3CuVtvhgMuxVVtvrMhuxt2dd9dv7uegvcguxLLLBzzTzR&seckey=zDIsqbZmzyHx6eOVvfO7Y2qo2HOfw9QZCxsBcSz%2FaHg%' \
          '3D%2C4dj7-lQyR8v3WrKsrV8Ddt9Ihj03T9l-ug2fSK8tBCNuCFmv1idEuI8CjOL7MVkyCoYk6zqegy9-2DHioRcWLblkMjgwL5vsV4eudvmN49hvbNgPTr' \
          'JM5Bt5TRbevQfiDEKaA5L4YLo7IwBnEgA9lG_V5Lq-Dt2Z0UvRJJEk3kStnBo0MQNsZNSZxZZPmHlv&tn=B_NORMAL_MAP&nn=0&u_loc=12618752,2635228&' \
          'ie=utf-8&t=1666322929658&newfrom=zhuzhan_webmap'      # API接口
    getData(url)    # 调用getData()函数
